/*
 * @Author: 谢陈洁
 * @Date: 2025-07-23 11:23:58
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-07-29 15:55:39
 * @Description: file content
 */
import { useUserStore } from "@/stores/userStore";
import { gernarateRoutes } from '@/utils/route';
export function setupGuards(router: any) {
  let addFlag = false
  router.beforeEach(async (to: any, from: any, next: any) => {
    const userStore = useUserStore()
    // 白名单处理
    const whiteList = ['/login', '/404']
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 权限校验 非白名单，判断是否登录
      if (!userStore.token) return next('/login')
      console.log('userStore.dynamicMenus', userStore.dynamicMenus)
      // 动态路由加载
      if (!addFlag) { // 添加动态路由
        console.log('动态路由加载')
        try {
          const { menus } = await userStore.getPermissions()
          const dynamicRoutes = gernarateRoutes(menus)
          dynamicRoutes.forEach(route => {
            router.addRoute(route)
          })
          userStore.setRoutes(dynamicRoutes)
          localStorage.setItem('menuList', JSON.stringify(dynamicRoutes))
          addFlag = true
          next({ ...to, replace: true })
        } catch (error) {
          next('/login')
        }
      } else {
        next()
      }
    }
  })
}
